/*
 * MultiRtpMediaChannel.h
 *
 *  Created on: 2018年5月1日
 *      Author: zhengboyuan
 */

#ifndef MULTIRTPMEDIACHANNEL_H_
#define MULTIRTPMEDIACHANNEL_H_

#include "RtpMediaChannel.h"
#include "MediaSourceExT.h"
#include "RtpSocket.h"
#include "RtpType.h"
#include "MediaPacketQueue.h"
#include "RtpPacker.h"
#include "TThread.h"


namespace av
{

class MultiRtpMediaChannel: public MediaSourceExT<RtpMediaChannel>, public comn::Thread
{
public:
	static const int DEFAULT_TIMEOUT = 1000 * 3;
	static const int TRY_COUNT = 3;

public:
	explicit MultiRtpMediaChannel(RtpProtocol protocol);
	virtual ~MultiRtpMediaChannel();

	virtual int open(const std::string& url, const std::string& params);
	virtual void close();
	virtual bool isOpen();

	virtual int startStream();

	virtual int pauseStream();

	virtual void stopStream();

	virtual int forceKeyFrame();


    virtual void onMediaFormat(const MediaFormat& fmt);

    virtual void onMediaPacket(MediaPacketPtr& pkt);

    virtual void onMediaEvent(int event);


	virtual NetAddress getLocalAddr();

	virtual void setMaxPacetSize(size_t size);

    virtual void setPayload(uint8_t payload);

    virtual uint8_t getPayload();

    virtual void setSsrc(uint32_t ssrc);

    virtual uint32_t getSsrc();

	virtual void setStreamMode(int mode);

	virtual int getStreamMode();


    virtual void setPeerAddr(const std::string& ip, int port);

	virtual void setPeerMedium(const std::string& mediaType, int payload, const std::string& codec, int clockrate, const std::string& sprop);

	virtual NetAddress getPeerAddr();

public:
	void handleRecv();
	void cancelRecv();

protected:
    virtual int run();
    virtual void doStop();

protected:
	RtpSocket* createSocket(RtpProtocol protocol);

	void sendPacket(MediaPacketPtr& pkt);

	void setupPacker(const std::string& mediaType, int payload, const std::string& codec);

	void onRecvPacket(MediaPacket& packet);

	void sendRtpPacket(RtpPacket& packet);
	void handleRecvRtpPacket(RtpPacket& packet);
    
protected:
	RtpProtocol	m_protocol;
	std::shared_ptr<RtpSocket>	m_socket;
	NetAddress	m_peerAddress;

	int		m_streamMode;
	uint8_t	m_payload;
	uint32_t	m_ssrc;
	size_t		m_maxPktSize;

	MediaPacketQueue    m_pktQueue;

	std::shared_ptr< RtpPacker >	m_rtpPacker;
	std::shared_ptr< RtpUnPacker >	m_rtpUnPacker;

	std::shared_ptr< comn::Thread>	m_recvThread;

	bool	m_formatReady;
    

};


} /* namespace av */

#endif /* MULTIRTPMEDIACHANNEL_H_ */
